import React, { useCallback, useEffect, useState } from 'react';
import { Modal, Button, Form, Input, Space, Select } from 'antd';

const { Option } = Select;

const wrapperCol = { offset: 8, span: 16 };

interface AddOrEditProps {
  visible: boolean;
  onCancelWrite: () => void;
  flag: string;
  onSubmit: (valuse: any) => void;
  selectData: any[];
  rowRecord: any;
}

const AddOrEdit: React.FC<AddOrEditProps> = ({
  visible,
  onCancelWrite,
  flag,
  onSubmit,
  selectData,
  rowRecord,
}) => {
  const [form] = Form.useForm();
  const handleCancel = useCallback(() => {
    onCancelWrite();
    form.resetFields();
  }, [onCancelWrite, form]);

  const handleFinsh = useCallback(
    (values) => {
      onSubmit(values);
    },
    [onSubmit],
  );

  const handleReset = useCallback(() => {
    form.resetFields();
  }, [form]);

  useEffect(() => {
    if (flag === 'edit') {
      form.setFieldsValue(rowRecord);
    } else if (flag === 'add') {
      form.resetFields();
    }
  }, [flag, form, rowRecord]);

  return (
    <Modal
      title={flag === 'add' ? '添加分类' : '分类名称'}
      visible={visible}
      onCancel={handleCancel}
      footer={null}
      forceRender={true}
      destroyOnClose={true}
    >
      <Form
        form={form}
        onFinish={handleFinsh}
        preserve={false}
        layout="vertical"
      >
        <Form.Item
          label="父级分类"
          name="pid"
          rules={[{ required: true, message: '请选择分类' }]}
        >
          <Select>
            {selectData.map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="分类名称"
          name="name"
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input placeholder="请输入分类名称" />
        </Form.Item>

        <Form.Item wrapperCol={wrapperCol}>
          <Space>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddOrEdit;
